package br.uefs.dexa.rfframework.strategies.lire;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.imageio.ImageIO;

import net.semanticmetadata.lire.DocumentBuilder;
import net.semanticmetadata.lire.ImageSearchHits;
import net.semanticmetadata.lire.ImageSearcher;
import net.semanticmetadata.lire.ImageSearcherFactory;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.FSDirectory;

import br.uefs.dexa.rfframework.config.AppConfigManager;
import br.uefs.dexa.rfframework.db.map.MapDatabaseManager;
import br.unicamp.ic.lis.rfframework.impl.interfaces.ICollectionOrganizationStrategy;
import br.unicamp.ic.lis.rfframework.objects.DigitalObject;
import br.unicamp.ic.lis.rfframework.objects.DigitalObjectSet;
import br.unicamp.ic.lis.rfframework.objects.IDigitalObject;
import br.unicamp.ic.lis.rfframework.objects.LabeledDigitalObject;
import br.unicamp.ic.lis.rfframework.objects.exceptions.EmptyCollectionException;
import br.unicamp.ic.lis.rfframework.objects.exceptions.ObjectNotFoundException;

public class LireCollectionOrganizer implements ICollectionOrganizationStrategy {
	
	@Override
	public DigitalObjectSet<DigitalObject> run(
			DigitalObjectSet<DigitalObject> collection,
			DigitalObjectSet<LabeledDigitalObject> queryPattern,
			DigitalObjectSet<LabeledDigitalObject> labeledObjects) {
		
		
		
		DigitalObjectSet<DigitalObject> result = new DigitalObjectSet<DigitalObject>();
		
		
        BufferedImage img = null;


        IDigitalObject obj;
		try {
			//obj = queryPattern.getObjectByIndex(0);
			obj = labeledObjects.getObjectByIndex(labeledObjects.getSize()-1);
		} catch (ObjectNotFoundException e1) {
			e1.printStackTrace();
			return null;
		} catch (EmptyCollectionException e1) {
			e1.printStackTrace();
			return null;
		}
        
        String queryImgPath = MapDatabaseManager.getInstance().getImagePath(obj.getId());
        
       File f = new File(queryImgPath);
       if (f.exists()) {
          try {
              img = ImageIO.read(f);
          } catch (IOException e) {
              e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
          }
       }
  
    
        IndexReader ir;
		try {
			String indexFile = AppConfigManager.getInstance().getLireIndexFile();
			//ir = DirectoryReader.open(FSDirectory.open(new File(INDEX_FILE)));
			ir = DirectoryReader.open(FSDirectory.open(new File(indexFile)));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		int numberOfObjects = AppConfigManager.getInstance().getNumberOfRetrievedObjectsShown();
		ImageSearcher searcher = ImageSearcherFactory.createCEDDImageSearcher(numberOfObjects);

        ImageSearchHits hits;
		try {
			hits = searcher.search(img, ir);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		
        for (int i = 0; i < hits.length(); i++) {
            String fileName = hits.doc(i).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
        	long objId = MapDatabaseManager.getInstance().getIdFromImagePath(fileName);
            
            result.addObject(new DigitalObject(objId));
        	
           // System.out.println(hits.score(i) + ": \t" + fileName);
        }
		
//		Set<Document> positives = new HashSet();
//		Set<Document> negatives = new HashSet();
//		
//		for (int i = 0; i < labeledObjects.getSize(); i++) {
//			for (int j = 0; j < hits.length(); j++) {
//				
//				IDigitalObject object;
//				try {
//					object = labeledObjects.getObjectByIndex(i);
//				} catch (ObjectNotFoundException e) {
//					e.printStackTrace();
//					return null;
//				} catch (EmptyCollectionException e) {
//					e.printStackTrace();
//					return null;
//				}
//				String fileName = hits.doc(i).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
//				String imagePath = MapDatabaseManager.getInstance().getImagePath(object.getId());
//				
//				if(fileName.equals(imagePath))
//					positives.add(hits.doc(i));
//				
//				break;
//				
//			}
//		}
//		
//		  ImageSearchHits newHits;
//			//newHits = searcher.search(img, ir);
//			newHits = searcher.relevanceFeedback(hits, positives, negatives);
//		
//		for (int i = 0; i < newHits.length(); i++) 
//		{
//			String fileName = newHits.doc(i).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
//			long objId = MapDatabaseManager.getInstance().getIdFromImagePath(fileName);
//			result.addObject(new DigitalObject(objId));
//
//			System.out.println(newHits.score(i) + ": \t" + fileName);
//		}
		
        
        return result;
		
	}

}
